package com.cloudsigns.factorymanager2.project.activity;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.cloudsigns.factorymanager2.R;
import com.cloudsigns.factorymanager2.engineering.bean.EngineeringConstructContentBean;
import com.cloudsigns.factorymanager2.engineering.customview.DateViewDialog;
import com.cloudsigns.factorymanager2.project.adapter.ProductContentAdapter;
import com.cloudsigns.factorymanager2.project.adapter.ProductInformationAdapter;
import com.cloudsigns.factorymanager2.project.bean.ProductBean;
import com.cloudsigns.factorymanager2.project.iview.IAddEngineeringConstructOrderView;
import com.cloudsigns.factorymanager2.project.myinerface.ItemRemoveListener;
import com.cloudsigns.factorymanager2.project.presenter.AddEngineeringConstructOrderPresenter;
import com.cloudsigns.factorymanager2.project.utils.ConstantUtil;
import com.cloudsigns.factorymanager2.project.utils.DateUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

/**
 * 工程施工单
 * Created by tony on 2017/12/9.
 */

public class AddEngineeringConstructOrderActivity extends Activity implements OnGetGeoCoderResultListener,View.OnClickListener, ItemRemoveListener, IAddEngineeringConstructOrderView {
    private String TAG=AddEngineeringConstructOrderActivity.class.getSimpleName();
    private View rl_back;
    private TextView tv_title;
    private View ll_add_product;
    private ImageView img_add_product,img_add_construction_content;
    private ListView lv_add_product, lv_add_construction_content;
    private Button btn_save;
    private EditText  edt__project_name, edt__engineering_name, edt__engineering_address,edt__completion_date;
    private ImageView img_completion_date;
    private ProductInformationAdapter adapter;// 产品信息
    private ProductContentAdapter productContentAdapter;// 施工内容
    private List<ProductBean> productBeanList = new ArrayList<>();
    private List<EngineeringConstructContentBean> engineeringContentBeanList = new ArrayList<>();
    private AddEngineeringConstructOrderPresenter addEngineeringConstructOrderPresenter;
    private GeoCoder mSearch = null; // 搜索模块，也可去掉地图模块独立使用
    private double lat,lon;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        // 沉浸式状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    );
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN

                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);

        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        setContentView(R.layout.layout_engineering_construct_order);

        addEngineeringConstructOrderPresenter = new AddEngineeringConstructOrderPresenter(this);
        init();

        // 初始化搜索模块，注册事件监听
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(this);
    }

    private void init() {
        rl_back = findViewById(R.id.rl_back);
        tv_title = findViewById(R.id.tv_title);
        ll_add_product = findViewById(R.id.ll_add_product);
        img_add_product=findViewById(R.id.img_add_product);
        img_add_construction_content=findViewById(R.id.img_add_construction_content);
        lv_add_product = findViewById(R.id.lv_add_product);
        lv_add_construction_content = findViewById(R.id.lv_add_construction_content);
        btn_save = findViewById(R.id.btn_save);
        edt__completion_date = findViewById(R.id.edt__completion_date);
        img_completion_date=findViewById(R.id.img_completion_date);
        edt__project_name = findViewById(R.id.edt__project_name);
        edt__engineering_name = findViewById(R.id.edt__engineering_name);
        edt__engineering_address = findViewById(R.id.edt__engineering_address);

        tv_title.setText(getResources().getText(R.string.engineering_construct_order));
        rl_back.setOnClickListener(this);
        btn_save.setOnClickListener(this);
        ll_add_product.setOnClickListener(this);
        img_add_product.setOnClickListener(this);
        img_completion_date.setOnClickListener(this);
        img_add_construction_content.setOnClickListener(this);

        adapter = new ProductInformationAdapter(this, TAG);
        adapter.setRemoveListener(this);
        adapter.setData(productBeanList);
        lv_add_product.setAdapter(adapter);


        productContentAdapter = new ProductContentAdapter(this, TAG);
        productContentAdapter.setRemoveListener(this);
        productContentAdapter.setData(engineeringContentBeanList);
        lv_add_construction_content.setAdapter(productContentAdapter);
    }

    private void save() {
        if (TextUtils.isEmpty(edt__project_name.getText().toString().trim())){
            Toast.makeText(AddEngineeringConstructOrderActivity.this,"请输入项目名称",Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(edt__engineering_name.getText().toString().trim())){
            Toast.makeText(AddEngineeringConstructOrderActivity.this,"请输入工程名称",Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(edt__engineering_address.getText().toString().trim())){
            Toast.makeText(AddEngineeringConstructOrderActivity.this,"请输入详细地址",Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(edt__completion_date.getText().toString().trim())){
            Toast.makeText(AddEngineeringConstructOrderActivity.this,"请输入完成日期",Toast.LENGTH_SHORT).show();
            return;
        }


        mSearch.geocode(new GeoCodeOption()

//                .city(edt_engineering_city.getText().toString().trim())
                .address(edt__engineering_address.getText().toString().trim()));

//            addEngineeringConstructOrderPresenter.addEngineeringConstructOrder();
//        Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
//        finish();

    }

    private void showDateDialog() {
        DateViewDialog endDateChooseDialog = new DateViewDialog(this,
                new DateViewDialog.DateChooseInterface() {
                    @Override
                    public void getDateTime(String time, boolean longTimeChecked) {
                        edt__completion_date.setText(time);
                    }
                });
        endDateChooseDialog.setTimePickerGone(true);

        Calendar dateAndTime = Calendar.getInstance(Locale.getDefault());

        endDateChooseDialog.setDateDialogTitle(dateAndTime.get(Calendar.YEAR) + "-" + (dateAndTime.get(Calendar.MONTH) + 1) + "-" + dateAndTime.get(Calendar.DAY_OF_MONTH));
        endDateChooseDialog.showDateChooseDialog();
    }

    @Override
    public void remove(int positon) {  //列表中删除事件
        if (positon >= 0 && positon < productBeanList.size()) {
            productBeanList.remove(positon);
            adapter.setData(productBeanList);
            adapter.notifyDataSetChanged();
        }


        if (positon >= 0 && positon < engineeringContentBeanList.size()) {
            engineeringContentBeanList.remove(positon);
            productContentAdapter.setData(engineeringContentBeanList);
            productContentAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void remove(View view) {

    }

    @Override
    public void onClick(View view) {
        TextView tv;
        Intent mIntent;
        switch (view.getId()) {
            // 返回
            case R.id.rl_back:
                finish();
                break;
                // 产品信息
            case R.id.img_add_product:
//                mIntent = new Intent(AddEngineeringConstructOrderActivity.this, AddProductInfomationActivity.class);
                mIntent = new Intent(AddEngineeringConstructOrderActivity.this, AddProductInfomationActivity1.class);
                mIntent.putExtra("type","engineeringConstruct");
                startActivityForResult(mIntent, ConstantUtil.ADD_PRODUCT_INFOMATION);
                break;
                // 保存
            case R.id.btn_save:
                save();
                break;
                // 日期
            case R.id.img_completion_date:
                showDateDialog();
                break;
                //施工内容
            case R.id.img_add_construction_content:
                EngineeringConstructContentBean eConstructContentBean = new EngineeringConstructContentBean();
                eConstructContentBean.setConstructPart("");
                engineeringContentBeanList.add(eConstructContentBean);
                productContentAdapter.setData(engineeringContentBeanList);
                productContentAdapter.notifyDataSetChanged();
                break;
        }
    }

    public void saveEditData(int position, String str) {
        Toast.makeText(this,str+"----"+position,Toast.LENGTH_LONG).show();

        if (null!=str||!TextUtils.isEmpty(str)){
            EngineeringConstructContentBean eConstructContentBean = new EngineeringConstructContentBean();
            eConstructContentBean.setConstructPart(str);
            engineeringContentBeanList.add(eConstructContentBean);
            productContentAdapter.setData(engineeringContentBeanList);
            productContentAdapter.notifyDataSetChanged();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case ConstantUtil.ADD_PRODUCT_INFOMATION: //添加产品信息
                if (data != null) {
                    ProductBean productBean = (ProductBean) data.getSerializableExtra(ConstantUtil.PRODUCTBEAN);
                    if (productBean != null) {
                        productBeanList.add(productBean);
                        adapter.setData(productBeanList);
                        adapter.notifyDataSetChanged();
                    }


                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public long getCompleteDate() {
        long mills = DateUtil.getMillis(edt__completion_date.getText().toString().trim());
        String date = DateUtil.getYyyy_Mm_Dd(mills);
        return mills;
    }

    @Override
    public List<EngineeringConstructContentBean> getConstructPartList() {
        return engineeringContentBeanList;
    }

    @Override
    public String getEngineeringAddress() {
        return edt__engineering_address.getText().toString().trim();
    }

    @Override
    public String getEngineeringName() {

        return edt__engineering_name.getText().toString().trim();
    }

    @Override
    public double getLat() {
        if (lat > 0 && lat <= 90 || lat < 0 && lat >= -90)
            return lat;
        else
            return 43.88; //默认 吉林省
    }

    @Override
    public double getLon() {
        if (lon > 0 && lon <= 180 || lon < 0 && lon >= -180)
            return lon;
        else
            return 125.25; //默认 吉林省
    }

    @Override
    public List<ProductBean> getProductList() {
        return productBeanList;
    }

    @Override
    public String getProjectName() {
        return edt__project_name.getText().toString().trim();
    }

    @Override
    public void addEngineeringConstructOrderSuccess(String projectId) {
        Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
        Intent mIntent = new Intent();
        mIntent.putExtra(ConstantUtil.KEY_1, true);
        setResult(ConstantUtil.CREATED_ORDER, mIntent);
        finish();
        Log.e(TAG,"addEngineeringConstructOrderSuccess projectId="+projectId);
    }

    @Override
    public void showFailedError(String desc) {
        Toast.makeText(this, "保存失败" + desc, Toast.LENGTH_SHORT).show();
        Log.e(TAG,"showFailedError desc="+desc);
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }


    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
        if (geoCodeResult == null || geoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(this, "请输入正确地址！", Toast.LENGTH_SHORT).show();
            return;
        }
        lat = geoCodeResult.getLocation().latitude;
        lon = geoCodeResult.getLocation().longitude;

        addEngineeringConstructOrderPresenter.addEngineeringConstructOrder();

    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {

    }

}
